package com.kfm.servlet;

import com.kfm.dao.UserDao;
import com.kfm.model.User;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// http://localhost:8080/user/login -- get doGet() login.html
// http://localhost:8080/user/login -- post doPost() 登录的逻辑判断
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 显示静态页面
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/login.html");
        requestDispatcher.forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端的请求参数 post 字节流获取字符流获取请求参数 getReader()
        // 将获取流的编码格式修改成 utf-8
        req.setCharacterEncoding("UTF-8"); // 将tomcat获取流的编码格式设置成 UTF-8
        resp.setCharacterEncoding("UTF-8");
//        System.out.println(req.getQueryString());
        String username = req.getParameter("username");
        String password = req.getParameter("pass");
        String captcha = req.getParameter("captcha");
        boolean ver = CaptchaUtil.ver(captcha, req);
        if (!ver) {
            CaptchaUtil.clear(req);
            System.out.println("验证码错误");
            resp.sendRedirect(req.getContextPath() + "/error");
        }
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        if (username != null && password != null ) {
            User user = userDao.selectByUsernameAndPassword(username, password);
            if (user == null) {
                // 如果错误就跳转到错误页面
                System.out.println("登录失败");
                // http://localhost:8080/user/error
                resp.sendRedirect(req.getContextPath() + "/error");
            } else {
                System.out.println("登录成功");
                resp.sendRedirect(req.getContextPath() + "/index");
            }
        } else {
            System.out.println("用户名或密码错误");
            resp.sendRedirect(req.getContextPath() + "/error");
        }
    }
}
